local skynet = require "skynet"
local cardsLib_n = require "DouDiZhu_n"
local cardsLib_3 = require "DouDiZhu_3"

require "luaext"

local internal = {}

function imap(tb, func)
    local rt = {}
    for i, v in ipairs(tb) do
        rt[i] = func(v)
    end
    return rt
end

function map(tb, func)
    local rt = {}
    for k, v in pairs(tb) do
        rt[k] = func(v)
    end
    return rt
end


local CARD_INDEX_CHAR = {
    B=102, C=103, D=104, E=105, F=106, G=107, H=108, I=109, J=110, K=111, L=112, M=113, A=101, 
    O=202, P=203, Q=204, R=205, S=206, T=207, U=208, V=209, W=210, X=211, Y=212, Z=213, N=201,
    b=302, c=303, d=304, e=305, f=306, g=307, h=308, i=309, j=310, k=311, l=312, m=313, a=301, 
    o=402, p=403, q=404, r=405, s=406, t=407, u=408, v=409, w=410, x=411, y=412, z=413, n=401,
    ['1']=14, ['2']=15}
    
local CARD_CHAR_INDEX = {}
for i, v in pairs(CARD_INDEX_CHAR) do
    CARD_CHAR_INDEX[i] = v
end

local function cardCharsToIndices( chars )
    local indices = {}
    for i = 1, #chars do
        indices[i] = CARD_CHAR_INDEX[string.sub(chars, i, i)] or 0
    end
    return indices
end

function table.keys( t )
    local keys = {}
    for k, _ in pairs( t ) do
        keys[#keys + 1] = k
    end
    return keys
end

function internal.get_ddz_cards(_, _, mode)
    --dbglog(mode)
	local cardsLib
	if mode == 'h' then
		cardsLib = cardsLib_h
	elseif mode == 'h2' then
		cardsLib = cardsLib_h2
	elseif mode == 'n' then
		cardsLib = cardsLib_n
    elseif mode == '3' then
        cardsLib = cardsLib_3
	end
	if not cardsLib then
		return skynet.retpack(false)
	end

	local snList = cardsLib.snList
	if not snList then
        snList = table.keys(cardsLib)
        table.mix(snList)
        cardsLib.snList = snList
    end

    local num = #snList
    local sn = snList[num]
    local allCards = cardsLib[sn]
    dbglog(sn,"allCards:",allCards)
    if type(allCards) == 'string' then
        allCards = imap(string.split(cardsLib[sn], ' '), cardCharsToIndices)
    end

    if num > 1 then
        table.remove(snList, num)
    else
        cardsLib.snList = nil
    end

    map(allCards, table.mix)
    --dbglog("allCards:",allCards)
    return skynet.retpack(allCards)
end

local function handle_request(session,source,action,...)
    dbglog('cards_library___action', action,...)
    local f = assert(internal[action],'unknown action ' .. action)
    f(session,source,...)
end

skynet.start(function()
	skynet.dispatch("lua",function(session,source,...)
		handle_request(session,source,...)
	end)
end)